package app.utils;

import org.apache.commons.lang3.StringUtils;

import java.util.Enumeration;

import javax.servlet.http.HttpServletRequest;

/**
 * 这个类用于在项目中获取相应的一些服务器路径
 * @author 昊琦
 *创建时间 2018年3月5日17:37:20
 */
public class BasePathCollector {
	
	/**
	 * 获取协议名
	 * @param request
	 * @return
	 */
	private static String getScheme(HttpServletRequest request){
		
		String scheme = request.getScheme();
		return StringUtils.isBlank(scheme) ? "" : scheme;
	}
	
	/**
	 * 获取服务器名
	 * @param request
	 * @return
	 */
	private static String getServerName(HttpServletRequest request){
		
		String serverName = request.getServerName();
		return StringUtils.isBlank(serverName) ? "" : serverName;
	}
	
	/**
	 * 获取端口号
	 * @param request
	 * @return
	 */
	private static int getPort(HttpServletRequest request){
		
		int serverPort = request.getServerPort();
		return serverPort < 0 ? 0 : serverPort;
	}
	
	/**
	 * 获取工程名
	 * @param request
	 * @return
	 */
	private static String getContextPath(HttpServletRequest request){
		String contextPath = request.getContextPath();
		return StringUtils.isBlank(contextPath) ? "" : contextPath;
	}
	
	/**
	 * 获取basePath带端口
	 * @param request
	 * @return
	 */
	public static String getBasePath(HttpServletRequest request){
		String scheme = getScheme(request);
		String serverName = getServerName(request);
		int port = getPort(request);
		String contextPath = getContextPath(request);

		return scheme+"://"+serverName+":"+port+contextPath+"/";
	}

	/**
	 * 获取basePath不带端口
	 * @param request
	 * @return
	 */
	public static String getBasePathWithoutPort(HttpServletRequest request){
		String scheme = getScheme(request);
		String serverName = getServerName(request);
		String contextPath = getContextPath(request);

		return scheme+"://"+serverName+contextPath+"/";
	}
	
	public static String getRequestUrl(HttpServletRequest request){
		StringBuffer requestURL = request.getRequestURL();
		Enumeration<String> params = request.getParameterNames();
		boolean flag=false;
		if (flag=params.hasMoreElements()) {
			requestURL = requestURL.append("?");
			while(flag){
				String nextElement = params.nextElement();
				requestURL.append(nextElement).append("=").append(request.getParameter(nextElement)).append("&");
				flag=params.hasMoreElements();
			}
			requestURL.deleteCharAt(requestURL.length()-1);
			if (requestURL.toString().contains("?pageNum")) {
				requestURL.delete(requestURL.indexOf("?pageNum"),requestURL.length());
			}
			if (requestURL.toString().contains("&pageNum")) {
				requestURL.delete(requestURL.indexOf("&pageNum"),requestURL.length());
			}
		}
		
		
		return requestURL.toString();
	}
}
